package com.dibang.app.mvp.gain;



import com.dibang.app.mvp.gain.exception.ExceptionHandler;
import com.dibang.app.mvp.gain.exception.UnKnowException;

import java.lang.reflect.ParameterizedType;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by wxl on 2019/5/20.
 */

public class DefaultSubscriber<T> implements Observer<HttpResult<T>> {

    private Callback<T> callback;

    private DisposableCallback disposableCallback;

    private DefaultSubscriber(Callback<T> callback, DisposableCallback disposableCallback) {
        this.callback = callback;
        this.disposableCallback = disposableCallback;
    }

    public static <T> DefaultSubscriber newInstance(Callback<T> callback, DisposableCallback disposableCallback) {
        return new DefaultSubscriber<T>(callback, disposableCallback);
    }

    @Override
    public void onSubscribe(Disposable d) {
        if (disposableCallback != null) {
            disposableCallback.onDisposable(d, findClazz());
        }
    }

    @Override
    public void onError(Throwable e) {
        Gain.get().dispose(findClazz().getName());
        if (callback != null) {
            callback.onFailed(e.getMessage());
        }
        ExceptionHandler.handlerException(e);
    }

    @Override
    public void onComplete() {
        Gain.get().dispose(findClazz().getName());
    }

    @Override
    public void onNext(HttpResult<T> result) {
        if (result.getCode() == 0) {
            if (callback != null) {
                callback.onSuccess(result.getData());
            }
            return;
        }
        if (callback != null) {
            callback.onFailed(result.getMsg());
        }
        ExceptionHandler.handlerException(new UnKnowException(result.getMsg(), result.getCode()));
    }

    private Class<T> findClazz() {
        ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        Class<T> clazz = (Class<T>) type.getActualTypeArguments()[0];
        return clazz;
    }
}
